//
// Created by root on 2020/5/3.
//

#include "RoomMgr.h"

#include "CommonFunction.h"

CRoomMgr::CRoomMgr() {

}

CRoomMgr::~CRoomMgr() {

}

void CRoomMgr::CreateRoom(const std::string &_sInitiator, const std::string &_sReceiver) {
    std::string sId = commonfunction::CreateUUID();
    CRoom oRoom(sId, _sInitiator, _sReceiver);
    m_setP2PChatRoom.insert(oRoom);
}

std::set<std::string> CRoomMgr::RemoveAndGetChater(const std::string &_sName) {
    std::set<std::string> setChater;    // 获取与该客户端正在聊天的客户端
    std::set<CRoom> setP2PRoom;
    for (const auto &index : m_setP2PChatRoom)
    {
        if (index.ContainChatName(_sName))
        {
            std::set<std::string> setClientId = index.GetClients();
            for (const auto &sClient : setClientId)
            {
                if (sClient != _sName)
                {
                    setChater.insert(sClient);
                }
            }
        }
        else{
            setP2PRoom.insert(index);
        }
    }
    m_setP2PChatRoom = setP2PRoom;
    return setChater;
}

void CRoomMgr::CloseRoom(const std::string &_sRoomId) {
    for (auto iter = m_setP2PChatRoom.begin(); iter != m_setP2PChatRoom.end(); iter++)
    {
        if (iter->GetRoomId() == _sRoomId)
        {
            m_setP2PChatRoom.erase(iter);
            break;
        }
    }
}

void CRoomMgr::CloseRoom(const std::string &_csClientId1, const std::string &_csClientId2) {
    for (const auto &index : m_setP2PChatRoom)
    {
        std::set<std::string> setClienIds = index.GetClients();
        if (setClienIds.size() == 2)
        {
            if (setClienIds.find(_csClientId1) != setClienIds.end()
                && setClienIds.find(_csClientId2) != setClienIds.end())
            {
                this->CloseRoom(index.GetRoomId());
            }
        }
    }
}

bool CRoomMgr::IsContain(const std::string &_csClientId1, const std::string &_csClientId2) {
    for (const auto &index : m_setP2PChatRoom)
    {
        std::set<std::string> setClienIds = index.GetClients();
        if (setClienIds.size() == 2)
        {
            if (setClienIds.find(_csClientId1) != setClienIds.end()
            && setClienIds.find(_csClientId2) != setClienIds.end())
            {
                return true;
            }
        }
    }
    return false;
}
